<template>
  <div class="device-list">
    <ul class="global-operation-list" style="margin-top: 20px;">
      <li class="global-operation-left">
        <ul class="global-filter-list">
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">关键字：</h2>
            <el-input v-model="searchForm.keyword" @change="getPost" placeholder="昵称、手机号" clearable></el-input>
          </li>
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">用户类型：</h2>
            <el-select v-model="searchForm.userType" placeholder="请选择" clearable>
              <el-option v-for="item in userTypeOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </li>
          <li class="global-filter-item">
            <h2 class="global-filter-item-title">是否助理：</h2>
            <el-select v-model="searchForm.isAssistant" placeholder="请选择" clearable>
              <el-option v-for="item in isAssitantOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </li>

          <li class="global-filter-item global-filter-item-dateRange">
            <h2 class="global-filter-item-title">选择创建时间段：</h2>
            <el-date-picker v-model="searchForm.time" type="datetimerange" range-separator="至" value-format="timestamp"
              unlink-panels start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </li>

          <li class="global-filter-item">
            <el-button type="primary" class="global-filter-item-search" :style="{
                background: $store.state.theme.theme_color || '#03C192',
                border: 'none',
              }" @click="rePosts()">搜索</el-button>
          </li>
          <li class="global-filter-item">
            <el-button type="primary" class="global-filter-item-search" v-if="operationList.includes('add')"
              @click="add">添加</el-button>
          </li>
        </ul>
      </li>
    </ul>
    <div class="global-table-content">
      <div class="global-table">
        <el-table :data="dataList" :header-cell-style="{
            background: '#F6F7FA',
            color: '#333',
            height: '60px',
          }" v-loading="tableLoading" :row-style="{ height: '0' }" :cell-style="{ padding: '3px' }" max-height="700"
          ref="multipleTable" @selection-change="handleSelectionChange"
          :default-sort="{ prop: 'createTime', order: 'descending' }" v-if="dataList && dataList.length > 0">
          <el-table-column prop="nickName" label="昵称" show-overflow-tooltip></el-table-column>
          <!-- <el-table-column
            prop="headPic"
            label="列表图片"
          >
            <template slot-scope="scope">
              <el-image style="width: 50px; height: 50px" :src="scope.row.headPic" :preview-src-list="[scope.row.headPic]" fit="contain">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>
          </el-table-column> -->

          <el-table-column label="手机号" prop="telephone" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.telephone ? scope.row.telephone : "--" }}
            </template>
          </el-table-column>

          <el-table-column label="用户类型" prop="userType" show-overflow-tooltip>
            <template slot-scope="scope">
              {{
              scope.row.userType
              ? scope.row.userType == 1
              ? "渠道商"
              : scope.row.userType == 2
              ? "渠道开拓者"
              : scope.row.userType == 3
              ? "订单发布者"
              : scope.row.userType == 4
              ? "CEO"
              : scope.row.userType == 5
              ? "媒体方"
              : "其他"
              : "--"
              }}
            </template>
          </el-table-column>

          <el-table-column prop="pioneerName" label="开拓者姓名" show-overflow-tooltip></el-table-column>

          <el-table-column prop="directorName" label="负责人姓名" show-overflow-tooltip></el-table-column>
          <el-table-column prop="province" label="地址" show-overflow-tooltip>
            <template slot-scope="scope">
              {{
              scope.row.province +
              scope.row.city +
              scope.row.area +
              scope.row.address
              }}
            </template>
          </el-table-column>

          <el-table-column prop="userLevelName" label="等级" show-overflow-tooltip></el-table-column>
          <el-table-column prop="isAssistant" label="是否助理" show-overflow-tooltip>
            <template slot-scope="scope">
              <div>
                {{
                scope.row.isAssistant
                ? scope.row.isAssistant == 1
                ? "否"
                : scope.row.isAssistant == 2
                ? "助理"
                : "-"
                : "--"
                }}
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="assistantUserNames" label="助理所属开拓者" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="marginPrice" label="押金" show-overflow-tooltip></el-table-column>

          <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip></el-table-column>

          <el-table-column prop="lastLoginTime" label="最后登录时间" show-overflow-tooltip></el-table-column>

          <el-table-column fixed="right" label="操作" width="200px">
            <template slot-scope="scope">
              <el-dropdown @command="handleCommand($event, scope.row)">
                <span class="el-dropdown-link" :style="{
                    color: $store.state.theme.theme_color || '#03C192',
                    cursor: 'pointer',
                  }">
                  操作
                </span>
                <el-dropdown-menu slot="dropdown">
                  <!-- <el-dropdown-item command="1" v-if="operationList.includes('editUserType')">修改用户类型</el-dropdown-item> -->
                  <el-dropdown-item command="2" v-if="operationList.includes('editUserName')">修改用户名称</el-dropdown-item>
                  <el-dropdown-item command="3" v-if="operationList.includes('edit')">修改</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <!-- <div>
                <el-button v-if="operationList.includes('editUserType')" style="font-size: 14px;" type="text" @click="handleCommand(1, scope.row)">修改用户类型</el-button>
              </div>
              <div>
                <el-button v-if="operationList.includes('editUserName')" style="font-size: 14px;" type="text" @click="handleCommand(2, scope.row)">修改用户名称</el-button>
              </div>
              <div>
                <el-button v-if="operationList.includes('edit')" style="font-size: 14px;margin-left: 20px" type="text" @click="handleCommand(3, scope.row)">修改</el-button>
              </div> -->
              <!-- <el-button v-if="operationList.includes('del')" style="font-size: 14px;margin-left: 20px" type="text" @click="handleCommand(3, scope.row)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <div class="no-data" v-else
          style="height: calc(100vh - 130px - 80px);display: flex;align-items: center;justify-content: center;flex-direction: column">
          <img style="width: 265px;height: 120px;margin-bottom: 32px" src="@/assets/images/tyNoData.png" alt="" />
          <div style="font-size: 16px;color: #A5A9B5">暂无数据~</div>
        </div>
      </div>
      <div class="global-page">
        <div class="global-page-left"></div>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="pageSizes"
          :page-size="pageSize" :current-page="pageNum" background layout="sizes, total, prev, pager, next"
          :total="total"></el-pagination>
      </div>
    </div>

    <el-dialog :title="editDialogTitle" :visible.sync="editDialog" :width="editDialogWidth" :before-close="handleClose"
      custom-class="editDialog">
      <div>
        <el-radio v-model="chooseUserType" v-for="item in userTypeOptions" :key="item.value" :label="item.value">{{
          item.label }}</el-radio>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="updateUserType">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="editDialogNameTitle" :visible.sync="editDialogName" :width="editDialogNameWidth"
      :before-close="handleCloseName" custom-class="editDialog">
      <div>
        <el-input v-model="chooseUserName" placeholder="请输入昵称"></el-input>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogName = false">取 消</el-button>
        <el-button type="primary" @click="updateUserName">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog :title="msgDialogTitle" :visible.sync="msgDialogFormVisible">
      <el-form :model="msgForm" :rules="msgRules" ref="ruleForm">
        <el-form-item label="昵称" prop="nickName" :label-width="formLabelWidth">
          <el-input v-model="msgForm.nickName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="telephone" :label-width="formLabelWidth">
          <el-input v-model="msgForm.telephone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="负责人姓名" prop="directorName" :label-width="formLabelWidth">
          <el-input v-model="msgForm.directorName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="身份证" prop="idCard" :label-width="formLabelWidth">
          <el-input v-model="msgForm.idCard" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex" :label-width="formLabelWidth">
          <el-radio-group v-model="msgForm.sex">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="用户类型" prop="userType" :label-width="formLabelWidth">
          <el-radio-group v-model="msgForm.userType">
            <el-radio :label="1">渠道商</el-radio>
            <el-radio :label="2">渠道开拓者</el-radio>
            <el-radio :label="3">订单发布者</el-radio>
            <el-radio :label="4">CEO</el-radio>
            <el-radio :label="5">媒体方</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="媒体方" prop="mediaPartyId" :label-width="formLabelWidth" v-if="msgForm.userType == 5">
          <el-select filterable multiple v-model="msgForm.mediaPartyId" placeholder="请选择渠道方">
            <el-option v-for="(item, index) in mediaPartyList" :key="index" :label="item.mediaPartyName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否助理" prop="isAssistant" :label-width="formLabelWidth" v-if="msgForm.userType == 2">
          <el-radio-group v-model="msgForm.isAssistant">
            <el-radio :label="2">是</el-radio>
            <el-radio :label="1">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="渠道开拓者" prop="assistantUserIds" :label-width="formLabelWidth"
          v-if="msgForm.isAssistant == 2 && msgForm.userType == 2">
          <el-select filterable multiple v-model="msgForm.assistantUserIds" placeholder="请选择开拓者">
            <el-option v-for="(item, index) in pushList" :key="index" :label="item.nickName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否游客" prop="touristType" :label-width="formLabelWidth" v-if="msgForm.userType == 1">
          <el-radio-group v-model="msgForm.touristType">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">游客</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="省" prop="province" :label-width="formLabelWidth">
          <el-input v-model="msgForm.province" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="市" prop="city" :label-width="formLabelWidth">
          <el-input v-model="msgForm.city" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="区" prop="area" :label-width="formLabelWidth">
          <el-input v-model="msgForm.area" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address" :label-width="formLabelWidth">
          <el-input v-model="msgForm.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="渠道开拓者" prop="pushUserId" :label-width="formLabelWidth" v-if="msgForm.userType == 1">
          <el-select v-model="msgForm.pushUserId" placeholder="请选择">
            <el-option v-for="(item, index) in pushList" :key="index" :label="item.nickName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道等级" prop="userLevel" :label-width="formLabelWidth" v-if="msgForm.userType == 1">
          <el-select v-model="msgForm.userLevel" placeholder="请选择">
            <el-option v-for="(item, index) in userLevelList" :key="index" :label="item.sysValueName"
              :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="押金" prop="marginPrice" :label-width="formLabelWidth" v-if="msgForm.userType == 1">
          <el-input v-model="msgForm.marginPrice" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="msgDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitMsg">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import APIUser from "@/api/apiUser";
import APIMediaParty from "@/api/apiMediaParty";
import APISysLabel from "@/api/apiSysLabel";

export default {
  name: "UserList",
  props: {
    operationList: Array,
  },
  data() {
    return {
      userTypeOptions: [
        {
          value: 1,
          label: "渠道商",
        },
        {
          value: 2,
          label: "渠道开拓者",
        },
        {
          value: 3,
          label: "订单发布者",
        },
      ],
      isAssitantOptions: [
        {
          value: 1,
          label: "否",
        },
        {
          value: 2,
          label: "是",
        },
      ],
      tokenData: {
        token: localStorage.getItem("mujingtoken"),
      },
      searchForm: {
        status: null,
        time: "",
        keyword: "",
        startTime: "",
        endTime: "",
        userType: null,
        isAssistant: null,
      },
      tableLoading: false,
      dataList: [],
      pushList: [],
      pushIds: null,
      pageSize: 20,
      pageNum: 1,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      editDialog: false,
      editDialogTitle: "",
      editDialogWidth: "80%",
      saveLoading: false,
      chooseUserId: null,
      chooseUserType: null,
      chooseUserName: "",
      editDialogName: false,
      editDialogNameTitle: "",
      editDialogNameWidth: "80%",
      msgDialogTitle: "新增用户",
      msgDialogFormVisible: false,
      formLabelWidth: "120px",
      msgForm: {
        idCard: "",
        nickName: "",
        telephone: "",
        sex: 1,
        province: "",
        city: "",
        area: "",
        address: "",
        directorName: "",
        userType: 1,
        pushUserId: null,
        touristType: 1,
        userLevel: null,
        marginPrice: "",
        isAssistant: 1,
        assistantUserIds: [],
        mediaPartyId: [],
      },
      msgRules: {
        idCard: { required: true, message: "请输入身份证", trigger: "blur" },
        nickName: { required: true, message: "请输入昵称", trigger: "blur" },
        telephone: { required: true, message: "请输入手机号", trigger: "blur" },
        sex: { required: true, message: "请选择性别", trigger: "change" },
        directorName: {
          required: true,
          message: "请输入负责人姓名",
          trigger: "blur",
        },
        userType: {
          required: true,
          message: "请选择用户类型",
          trigger: "change",
        },
        pushUserId: {
          required: true,
          message: "请选择渠道开拓者",
          trigger: "change",
        },
        mediaPartyId: {
          required: true,
          message: "请选择渠道方",
          trigger: "change",
        },
      },
      userList: [],
      userLevelList: [],
      mediaPartyList: [],
    };
  },
  activated() {
    this.getSysLabelList();
    this.getPost();
  },
  created() {},
  mounted() {
    this.$bus.$on("clearSearchParams", () => {
      this.searchForm = {
        status: null,
        time: "",
        keyword: "",
        startTime: "",
        endTime: "",
        userType: null,
        isAssistant: null,
        mediaPartyId: [],
      };
    });
  },
  methods: {
    getMediaPartyList() {
      let params = {}
      APIMediaParty.getMediaPartyList(params).then((res) => {
        if (res.key === 1000) {
          res = res.result;
          this.mediaPartyList = res.list;
        }
      });
    },
    getSysLabelList() {
      const params = {
        token: this.$store.state.token,
        sysLabelIds: "22",
      };
      APISysLabel.getSysLabelValueManageList(params).then((res) => {
        if (res.key === 1000) {
          res = res.result;
          if (res.data) {
            this.userLevelList = res.data[22];
          }
        }
      });
    },
    getUserTypeList() {
      let params = {
        userType: 2,
      };
      if (this.chooseUserId) {
        params.userId = this.chooseUserId;
      }

      APIUser.getNormalUserList(params).then((res) => {
        if (res.key === 1000) {
          this.total = res.result.count;
          res = res.result.list;
          this.userList = res;
        }
      });
    },
    selectPushList() {
      const params = {
        token: this.$store.state.token,
      };

      APIUser.selectPushList(params).then((res) => {
        if (res.key === 1000) {
          this.pushList = res.result.list;
        }
      });
    },
    add() {
      this.selectPushList();
      this.msgForm = {
        idCard: "",
        nickName: "",
        telephone: "",
        sex: 1,
        province: "",
        city: "",
        area: "",
        address: "",
        directorName: "",
        userType: 1,
        touristType: 1,
        marginPrice: "",
        userLevel: null,
        isAssistant: 1,
        assistantUserIds: [],
        mediaPartyId: [],
      };
      this.chooseUserId = null;
      this.msgDialogFormVisible = true;
      this.getUserTypeList();
      this.getMediaPartyList();
    },
    submitMsg() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$bus.$emit("show-loading", true);
          let params = {};
          params = this.msgForm;
          if (this.msgForm.assistantUserIds.length > 0) {
            params.assistantUserIds = this.msgForm.assistantUserIds.join(",");
          } else {
            params.assistantUserIds = null;
          }
          if (this.msgForm.mediaPartyId.length > 0) {
            params.mediaPartyId = this.msgForm.mediaPartyId.join(",");
          } else {
            params.mediaPartyId = null;
          }
          if (this.chooseUserId) {
            params.userId = this.chooseUserId;
            APIUser.doEditUser(params).then((res) => {
              if (res.key === 1000) {
                this.$message({
                  type: "success",
                  message: "提交成功",
                });
                this.msgDialogFormVisible = false;
                this.getPost();
              }
            });
          } else {
            APIUser.doAddUser(params).then((res) => {
              if (res.key === 1000) {
                this.$message({
                  type: "success",
                  message: "提交成功",
                });
                this.msgDialogFormVisible = false;
                this.rePosts();
              }
            });
          }
          this.$bus.$emit("show-loading", false);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    formatterTime(time) {
      if (time) {
        return this.$moment(new Date(time)).format("YYYY-MM-DD HH:mm:ss");
      } else {
        return "-";
      }
    },
    // 全选
    handleCheckAllChange() {
      this.$refs.multipleTable.toggleAllSelection();
    },
    // 表单选择
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 删除全部按钮
    handleDelAll() {
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        const ids = this.multipleSelection.map((item) => item.id);
        this.handleUpDeviceStatus([ids], 3);
      } else {
        this.$message({
          type: "warning",
          message: "请至少选择一项",
        });
      }
    },
    // 分页pageSize改变
    handleSizeChange(e) {
      this.pageSize = e;
      this.rePosts();
    },
    // 分页pageNum改变
    handleCurrentChange(e) {
      this.pageNum = e;
      this.getPost();
    },
    // 重新请求
    rePosts() {
      this.pageNum = 1;
      this.dataList = [];
      this.getPost();
    },
    handleCommand(e, row) {
      if (e == 1) {
        this.chooseUserId = row.id;
        this.chooseUserType = row.userType;
        this.editDialogTitle = "修改用户类型";
        this.editDialogWidth = "30%";
        this.editDialog = true;
      } else if (e == 2) {
        // 修改用户名称
        this.chooseUserId = row.id;
        this.chooseUserName = row.nickName;
        this.editDialogNameTitle = "修改用户名称";
        this.editDialogNameWidth = "30%";
        this.editDialogName = true;
      } else if (e == 3) {
        this.chooseUserId = row.id;
        // 修改用户信息
        let assistantUserIdList = [];
        this.selectPushList();
        this.getUserTypeList();
        this.getMediaPartyList()
        this.msgForm = row; 
        if (row.assistantUserIds) {
          row.assistantUserIds.split(",").forEach((item) => {
            assistantUserIdList.push(Number(item));
          });
        }
        this.msgForm.assistantUserIds = assistantUserIdList;
        let mediaPartyIdList = []
        if (row.mediaPartyId) {
          row.mediaPartyId.split(",").forEach((item) => {
            mediaPartyIdList.push(Number(item));
          });
        }
        this.msgForm.mediaPartyId = mediaPartyIdList;
        this.msgDialogTitle = "修改用户信息";
        this.msgDialogFormVisible = true;
      }
    },
    updateUserName() {
      this.$bus.$emit("show-loading", true);
      const params = {
        userId: this.chooseUserId,
        username: this.chooseUserName,
      };
      APIUser.doUpdateUserName(params).then((res) => {
        if (res.key === 1000) {
          this.$message.success({
            showClose: true,
            message: "修改成功",
            duration: 1500,
          });
          this.editDialogName = false;
          this.getPost();
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    updateUserType() {
      this.$bus.$emit("show-loading", true);
      const params = {
        userId: this.chooseUserId,
        userType: this.chooseUserType,
      };
      APIUser.doUpdateUserType(params).then((res) => {
        if (res.key === 1000) {
          this.$message.success({
            showClose: true,
            message: "修改成功",
            duration: 1500,
          });
          this.editDialog = false;
          this.getPost();
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    getPost() {
      this.$bus.$emit("show-loading", true);
      const params = {
        token: this.$store.state.token,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      };
      if (this.searchForm.keyword) {
        params.keyword = this.searchForm.keyword;
      }
      if (this.searchForm.userType) {
        params.userType = this.searchForm.userType;
      }
      if (this.searchForm.time) {
        params.startTime = this.searchForm.time[0];
        params.endTime = this.searchForm.time[1];
      }
      if (this.searchForm.isAssistant) {
        params.isAssistant = this.searchForm.isAssistant;
      }
      APIUser.getNormalUserList(params).then((res) => {
        if (res.key === 1000) {
          this.total = res.result.count;
          res = res.result.list;
          res.forEach((item) => {
            if (item.lastLoginTime) {
              item.lastLoginTime = this.$moment(item.lastLoginTime).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            }
            if (item.createTime) {
              item.createTime = this.$moment(item.createTime).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            }
          });
          this.dataList = res;
        }
        this.$bus.$emit("show-loading", false);
      });
    },
    handleCloseName() {
      this.editDialogName = false;
    },
    handleClose() {
      this.editDialog = false;
    },
  },
};
</script>

<style>
.mask-img-del-size {
  width: 50px;
  text-align: center;
  height: 50px;
  margin: 25px;
}
.mask-img {
  position: absolute;
  margin-top: -100px;
  width: 100%;
  height: 100%;
  bottom: 0;
  background: rgba(101, 101, 101, 0.6);
  color: #ffffff;
  opacity: 0;
  margin-left: -10px;
}
.banner-pic-sub .mask-img:hover {
  opacity: 1;
  cursor: pointer;
}
.el-upload__tip {
  color: #969799;
  margin-top: 0;
  height: 30px;
  line-height: 30px;
}
.avatar-uploader .el-upload .avatar-uploader-icon {
  width: 100px;
  height: 100px;
  line-height: 100px !important;
}
</style>

<style lang="sass">

.avatar-uploader-icon
  font-size: 28px
  color: #8c939d
  width: 178px
  height: 178px
  line-height: 178px !important
  text-align: center
.device-list
  padding-top: 26px
  @include container
.editDialog
  .el-dialog__header
    border-bottom: 1px solid #EFEFEF
    .el-dialog__headerbtn
      font-size: 20px
  .el-dialog__footer
    text-align: left
    margin-left: 120px
</style>
